package org.jeecg.modules.gzgl.controller;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhaodui.fxy.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.gzgl.entity.FxyGzgl07;
import org.jeecg.modules.gzgl.service.IFxyGzgl07Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.service.impl.SysDataLogServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

import static com.zhaodui.fxy.Base64Utils.download;

/**
 * @Description: 公证附件信息
 * @Author: zhaodui
 * @Date:   2020-02-06
 * @Version: V1.0
 */
@RestController
@RequestMapping("/gzgl/fxyGzgl07")
@Slf4j
public class FxyGzgl07Controller extends JeecgController<FxyGzgl07, IFxyGzgl07Service> {
	@Autowired
	private IFxyGzgl07Service fxyGzgl07Service;
	 @Autowired
	 private RedisUtil redisUtil;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
	@Autowired
	private SysDataLogServiceImpl sysDataLogService;
	/**
	 * 分页列表查询
	 *
	 * @param fxyGzgl07
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FxyGzgl07 fxyGzgl07,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FxyGzgl07> queryWrapper = QueryGenerator.initQueryWrapper(fxyGzgl07, req.getParameterMap());
		Page<FxyGzgl07> page = new Page<FxyGzgl07>(pageNo, pageSize);
		IPage<FxyGzgl07> pageList = fxyGzgl07Service.page(page, queryWrapper);
		return Result.ok(pageList);
	}


	@PostMapping(value = "/upload")
	public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
		Result<?> result = new Result<>();
		try {
			String ctxPath = uploadpath;
			String fileName = null;
			String bizPath = "files";
			String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
			File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
			String orgName = mf.getOriginalFilename();// 获取文件名
			fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
			String savePath = file.getPath() + File.separator + fileName;
			File savefile = new File(savePath);
			FileCopyUtils.copy(mf.getBytes(), savefile);
 			String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
			if (dbpath.contains("\\")) {
				dbpath = dbpath.replace("\\", "/");
			}

			try{
				FxyGzgl07 fxyGzgl07 = new FxyGzgl07();
				String appCode = request.getParameter("appcode");
				String orderno = request.getParameter("orderno");
				String filefrom = request.getParameter("filefrom");
				String filetype = request.getParameter("filetype");
				String userid = request.getParameter("userid");
				fxyGzgl07.setQuery01(appCode);
				fxyGzgl07.setQuery19(userid);
				fxyGzgl07.setQuery17(filetype);
				fxyGzgl07.setQuery12(filetype);
				fxyGzgl07.setQuery18(filefrom);
				fxyGzgl07.setQuery15(dbpath);

				fxyUser fxyUser = new fxyUser();
				fxyUser.setFileUrl(savePath);

				fxyUser.setUserId(fxyGzgl07.getQuery19());
				fxyUser.setFileName(fxyGzgl07.getQuery17());
				fxyUser.setFileType(fxyGzgl07.getQuery12());;
				fxyUser.setFrom(fxyGzgl07.getQuery18());
                String res = "";
				try{
                    File filein = new File(savePath);
                      res = fxyUtil.uploadFile(appCode,redisUtil,fxyUser,filein);
                }catch (BaseBusinessException e){
                    return Result.error(e.getMessage());

                }


				if(!StringUtil.isEmpty(res)){
					fxyGzgl07.setQuery14(res);

				}
				fxyGzgl07Service.save(fxyGzgl07);
 				result.setSuccess(true);

				return Result.okandt(res,dbpath);
			}catch (BaseBusinessException e){
				return Result.error(e.getMessage());
			}


		} catch (IOException e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 *   添加
	 *
	 * @param fxyGzgl07
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FxyGzgl07 fxyGzgl07) {
		if(StringUtil.isEmpty(fxyGzgl07.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl07.getQuery39())) {//不提交法信
			fxyGzgl07Service.save(fxyGzgl07);
			return Result.ok("添加成功！");
		}
		try{
            String appCode = fxyGzgl07.getQuery01();
            fxyUser fxyUser = new fxyUser();
            fxyUser.setFileUrl(fxyGzgl07.getQuery15());
            if(StringUtil.isNotEmpty(fxyUser.getFileUrl())){
                fxyUser.setFileUrl(savelocal(fxyUser.getFileUrl(),fxyUser.getFileName()));
            }
            fxyUser.setUserId(fxyGzgl07.getQuery19());
            fxyUser.setFileName(fxyGzgl07.getQuery17());
            fxyUser.setFileType(fxyGzgl07.getQuery12());;
            fxyUser.setFrom(fxyGzgl07.getQuery18());
            String res = fxyUtil.uploadFile(appCode,redisUtil,fxyUser);
			if(!StringUtil.isEmpty(res)){
				fxyGzgl07.setQuery14(res);
			}
		}catch (BaseBusinessException e){
			return Result.error(e.getMessage());
		}


		fxyGzgl07Service.save(fxyGzgl07);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl07);
		String id = fxyGzgl07.getId();
		sysDataLogService.addDataLog("fxy_gzgl_07",id,  datacont);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fxyGzgl07
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FxyGzgl07 fxyGzgl07) {
		if(StringUtil.isEmpty(fxyGzgl07.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl07.getQuery39())) {//不提交法信
			fxyGzgl07Service.updateById(fxyGzgl07);
			return Result.ok("编辑成功!");
		}
		try{
			String appCode = fxyGzgl07.getQuery01();
			fxyUser fxyUser = new fxyUser();
			fxyUser.setFileUrl(fxyGzgl07.getQuery15());
            if(StringUtil.isNotEmpty(fxyUser.getFileUrl())){
                fxyUser.setFileUrl(savelocal(fxyUser.getFileUrl(),fxyUser.getFileName()));
            }
			fxyUser.setUserId(fxyGzgl07.getQuery19());
			fxyUser.setFileName(fxyGzgl07.getQuery17());
			fxyUser.setFileType(fxyGzgl07.getQuery12());;
			fxyUser.setFrom(fxyGzgl07.getQuery18());
			String res = fxyUtil.uploadFile(appCode,redisUtil,fxyUser);
			if(!StringUtil.isEmpty(res)){
				fxyGzgl07.setQuery14(res);
			}
		}catch (BaseBusinessException e){
			fxyGzgl07.setQuery38(e.getMessage());
			fxyGzgl07Service.updateById(fxyGzgl07);
			return Result.error(e.getMessage());
		}
		fxyGzgl07Service.updateById(fxyGzgl07);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl07);
		String id = fxyGzgl07.getId();
		sysDataLogService.addDataLog("fxy_gzgl_07",id,  datacont);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		fxyGzgl07Service.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fxyGzgl07Service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FxyGzgl07 fxyGzgl07 = fxyGzgl07Service.getById(id);
		if(fxyGzgl07==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(fxyGzgl07);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fxyGzgl07
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FxyGzgl07 fxyGzgl07) {
        return super.exportXls(request, fxyGzgl07, FxyGzgl07.class, "公证附件信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FxyGzgl07.class);
    }
    //图片保存到本地
    public   String savelocal(String imgFile,String filename)
    {
        String imgpath = "";
        InputStream in = null;
        byte[] data = null;
        try
        {
            if(StringUtil.isNotEmpty(imgFile)){
                if(imgFile.startsWith("http")){//如果是网络图片则直接读取
                    String imgurl = imgFile;
                    String ctxPath= uploadpath;//demo中设置为D://upFiles,实际项目应因事制宜
                    String filest = DateUtils.date2Str(DateUtils.yyyymmddhhmmss);
                    imgpath=ctxPath+File.separator+filest +File.separator+filename;
                    File file = new File(ctxPath+File.separator+filest);
                    if (!file.exists()) {
                        file.mkdirs();// 创建文件根目录
                    }
                    System.out.println("imgurl="+imgurl);
                    download(imgurl,imgpath);
                }else{
                    String ctxPath= uploadpath;//demo中设置为D://upFiles,实际项目应因事制宜
                    imgpath=ctxPath+File.separator+imgFile;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return  imgpath;
    }
}
